// 生成随机数的函数
export const getRandomNumber = (min, max, num) => {
	if (num) {
		let arr = []
		for (var i = 0; i < num; i++) {
			let item = Math.floor(Math.random() * (max - min + 1)) + min;
			arr.push(item)
		}
		return arr
	} else {
		return Math.floor(Math.random() * (max - min + 1)) + min;
	}
}
/**
 * Parse the time to string
 * @param {(Object|string|number)} time
 * @param {string} cFormat
 * @returns {string | null}
 */
export function parseTime(time, cFormat) {
	if (arguments.length === 0 || !time) {
		return null
	}
	const format = cFormat || "{y}-{m}-{d} {h}:{i}:{s}"
	let date
	if (typeof time === "object") {
		date = time
	} else {
		if (typeof time === "string") {
			if (/^[0-9]+$/.test(time)) {
				// support "1548221490638"
				time = parseInt(time)
			} else {
				// support safari
				// https://stackoverflow.com/questions/4310953/invalid-date-in-safari
				time = time.replace(new RegExp(/-/gm), "/")
			}
		}

		if (typeof time === "number" && time.toString().length === 10) {
			time = time * 1000
		}
		date = new Date(time)
	}
	const formatObj = {
		y: date.getFullYear(),
		m: date.getMonth() + 1,
		d: date.getDate(),
		h: date.getHours(),
		i: date.getMinutes(),
		s: date.getSeconds(),
		a: date.getDay()
	}
	const time_str = format.replace(/{([ymdhisa])+}/g, (result, key) => {
		const value = formatObj[key]
		// Note: getDay() returns 0 on Sunday
		if (key === "a") {
			return ["日", "一", "二", "三", "四", "五", "六"][value]
		}
		return value.toString().padStart(2, "0")
	})
	return time_str
}

/**
 * @param {number} time
 * @param {string} option
 * @returns {string}
 */
export function formatTime(time, option) {
	if (("" + time).length === 10) {
		time = parseInt(time) * 1000
	} else {
		time = +time
	}
	const d = new Date(time)
	const now = Date.now()
	const diff = (now - d) / 1000

	if (diff < 30) {
		return "刚刚"
	} else if (diff < 3600) {
		// less 1 hour
		return Math.ceil(diff / 60) + "分钟前"
	}
	//  else if (diff < 3600 * 24) {
	// 	return Math.ceil(diff / 3600) + "小时前"
	// }
	//  else if (diff < 3600 * 24 * 2) {
	// 	return "1天前"
	// }
	if (option) {
		return parseTime(time, option)
	} else {
		return d.getMonth() + 1 + "月" + d.getDate() + "日" + d.getHours() + "时" + d.getMinutes() + "分"
	}
}

//时间格式化
export const formateDate = (datetime, type) => {
	var year = datetime.getFullYear(),
		month = ("0" + (datetime.getMonth() + 1)).slice(-2),
		date = ("0" + datetime.getDate()).slice(-2),
		hour = ("0" + datetime.getHours()).slice(-2),
		minute = ("0" + datetime.getMinutes()).slice(-2),
		second = ("0" + datetime.getSeconds()).slice(-2);
	if (type === "Y-M-D h:min:s") {
		var result = year + "-" + month + "-" + date + " " + hour + ":" + minute + ":" + second;
	} else if (type === "Y-M-D") {
		var result = year + "-" + month + "-" + date;
	} else if (type === "M-D") {
		var result = month + "-" + date;
	}
	if (type === "h:min:s") {
		var result = hour + ":" + minute + ":" + second;
	} else if (type === "h:min") {
		var result = hour + ":" + minute;
	} else if (type === "h") {
		var result = hour;
	} else if (type === "min") {
		var result = minute;
	}
	return result;
};

/**
 * base64ToBlob
 * @param {Object} urlData
 * @param {Object} type
 */
export const base64ToBlob = (urlData, type) => {
	let arr = urlData.split(",");
	let mime = arr[0].match(/:(.*?);/)[1] || type;
	// 去掉url的头，并转化为byte
	let bytes = window.atob(arr[1]);
	// 处理异常,将ascii码小于0的转换为大于0
	let ab = new ArrayBuffer(bytes.length);
	// 生成视图（直接针对内存）：8位无符号整数，长度1个字节
	let ia = new Uint8Array(ab);
	for (let i = 0; i < bytes.length; i++) {
		ia[i] = bytes.charCodeAt(i);
	}
	console.log(
		new Blob([ab], {
			type: mime,
		})
	);
	return new Blob([ab], {
		type: mime,
	});
};

/** @dateSurplus 计算开始时间到结束时间的时长
 * @startTime[必填]     Date      格林日期格式
 * @endTime[必填]     Date      格林日期格式
 * @format[可选,默认：s]
 * @return   '800'  String    返回示例
 * **/
export const dateSurplus = (startTime, endTime = "0", format = "秒") => {
	const start = new Date(startTime).getTime() / 1000;
	let end = 0;
	if (endTime) {
		end = new Date(endTime);
	} else {
		end = start + 86400;
	}
	return end - start;
};

/**
 * 计算两个经纬度之间的直线距离
 * @param {Object} start
 * @param {Object} end
 * let start = new LngLat(that.userLongitude, that.userLatitude)
	let end = new LngLat(item2.lon, item2.lat)
	let km = calculateLineDistance(start, end)
 */
export const calculateLineDistance = (start, end) => {
	var d1 = 0.01745329251994329;
	var d2 = start.longitude;
	var d3 = start.latitude;
	var d4 = end.longitude;
	var d5 = end.latitude;
	d2 *= d1;
	d3 *= d1;
	d4 *= d1;
	d5 *= d1;
	var d6 = Math.sin(d2);
	var d7 = Math.sin(d3);
	var d8 = Math.cos(d2);
	var d9 = Math.cos(d3);
	var d10 = Math.sin(d4);
	var d11 = Math.sin(d5);
	var d12 = Math.cos(d4);
	var d13 = Math.cos(d5);
	var arrayOfDouble1 = [];
	var arrayOfDouble2 = [];
	arrayOfDouble1.push(d9 * d8);
	arrayOfDouble1.push(d9 * d6);
	arrayOfDouble1.push(d7);
	arrayOfDouble2.push(d13 * d12);
	arrayOfDouble2.push(d13 * d10);
	arrayOfDouble2.push(d11);
	var d14 = Math.sqrt(
		(arrayOfDouble1[0] - arrayOfDouble2[0]) * (arrayOfDouble1[0] - arrayOfDouble2[0]) +
		(arrayOfDouble1[1] - arrayOfDouble2[1]) * (arrayOfDouble1[1] - arrayOfDouble2[1]) +
		(arrayOfDouble1[2] - arrayOfDouble2[2]) * (arrayOfDouble1[2] - arrayOfDouble2[2])
	);

	return parseFloat((Math.asin(d14 / 2.0) * 12742001.579854401) / 1000).toFixed(2);
};

/*
 * JSON数组去重
 * @param: [array] json Array
 * @param: [string] 唯一的key名，根据此键名进行去重
 */

export const uniqueArray = (array, key) => {
	var result = [array[0]];
	for (var i = 1; i < array.length; i++) {
		var item = array[i];
		var repeat = false;
		for (var j = 0; j < result.length; j++) {
			if (item[key] === result[j][key]) {
				repeat = true;
				break;
			}
		}
		if (!repeat) {
			result.push(item);
		}
	}
	return result;
};

/**
 * 深拷贝
 * @param {*} data
 */
export const deepClone = (data) => {
	let type = getObjType(data);
	let obj;
	if (type === "array") {
		obj = [];
	} else if (type === "object") {
		obj = {};
	} else {
		//不再具有下一层次
		return data;
	}
	if (type === "array") {
		for (let i = 0, len = data.length; i < len; i++) {
			obj.push(deepClone(data[i]));
		}
	} else if (type === "object") {
		for (let key in data) {
			obj[key] = deepClone(data[key]);
		}
	}
	return obj;
};
/**
 * 删除对象中的空值
 * @param {Object} form
 */
export const delObjNull = (form) => {
	let obj = uni.$u.deepClone(form);
	for (let key in obj) {
		if (key.indexOf("$") >= 0 || obj[key] === "" || obj[key] === null || obj[key] === undefined) {
			delete obj[key];
		}
	}
	return obj;
};

/**
 * 获取文件类型
 * @param {*} path
 */
export const getFileTypeByPath = (path) => {
	let index = path.lastIndexOf("."); // lastIndexOf("/")  找到最后一个  /  的位置
	let fileType = path.substr(index + 1); // substr() 截取剩余的字符，即文件名doc
	return fileType;
};
/**
 * 下载文件
 * @param {*} blob
 * @param {*} tagFileName
 * @param {*} fileType
 */
export const downloadFile = (blob, tagFileName, fileType) => {
	let downloadElement = document.createElement("a");
	let href = blob;
	if (typeof blob == "string") {
		downloadElement.target = "_blank";
	} else {
		href = window.URL.createObjectURL(blob); //创建下载的链接
	}
	downloadElement.href = href;
	downloadElement.download = tagFileName + moment(new Date().getTime()).format("YYYYMMDDhhmmss") + "." +
		fileType; //下载后文件名
	document.body.appendChild(downloadElement);
	downloadElement.click(); //点击下载
	document.body.removeChild(downloadElement); //下载完成移除元素
	if (typeof blob != "string") {
		window.URL.revokeObjectURL(href); //释放掉blob对象
	}
};

export const isImage = (file) => {
	//判断是否是图片 - strFilter必须是小写列举
	const strFilter = ".jpeg|.gif|.jpg|.png|.bmp|.pic|.svg|";
	if (file.indexOf(".") > -1) {
		let p = file.lastIndexOf(".");
		let strPostfix = file.substring(p, file.length) + "|";
		strPostfix = strPostfix.toLowerCase();
		if (strFilter.indexOf(strPostfix) > -1) {
			return true;
		}
	}
	return false;
};